<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:'/home/users'}">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 筛选栏 -->
    <div style="margin: 15px 0">
      <el-input
        v-model="query"
        placeholder="请输入内容"
        @keyup.enter.native="search"
        class="input-with-select"
        style="width:300px"
      >
        <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
      </el-input>
      <el-button
        style="margin-left:15px"
        type="success"
        @click="addDialogFormVisible=true"
        plain
      >添加用户</el-button>
    </div>

    <!-- 用户列表展示区域 -->
    <el-table :data="userInfo" border style="width: 100%" highlight-current-row>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="160"></el-table-column>
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="editUserStatus(scope.row.id,scope.row.mg_state)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑用户" placement="top">
            <el-button type="info" icon="el-icon-edit" @click="editUser(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="light" content="配置角色" placement="top">
            <el-button type="success" icon="el-icon-share" @click="showRoleFormVisible(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除用户" placement="top">
            <el-button type="warning" icon="el-icon-delete" @click="deluser(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页按钮部分 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 3, 4, 5]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 添加用户弹窗部分 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" ref="addForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配用户角色弹窗部分 -->
    <el-dialog title="分配角色" :visible.sync="configureRoleFormVisible">
      <el-form :model="configureForm" :label-width="'120px'">
        <el-form-item label="用户名" :style="'width:260px'">
          <el-input v-model="configureForm.username" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="configureForm.rid " clearable placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="configureUserRoleSub">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户弹窗部分 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editUserForm" ref="editUserForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 引入api模块
import { Message } from 'element-ui'
import {
  getUsers,
  askAddNewUser,
  delUserById,
  editUserById,
  updateUserState,
  configureUserRole
} from '@/api/user_api.js'
import { getAllRolesList } from '@/api/roles_api.js'
export default {
  data () {
    return {
      // 用户状态
      myUserStatus: '',
      // 全部角色列表
      rolesList: '',
      // 分配角色信息
      configureForm: {
        username: '',
        id: '',
        rid: ''
      },
      value4: '',
      // 用户搜索关键字
      query: '',
      //   当前页码
      pagenum: 1,
      //   每页显示的记录数
      pagesize: 5,
      total: null,
      userInfo: [
        {
          username: '',
          email: '',
          mobile: ''
        }
      ],
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      configureRoleFormVisible: false,
      addForm: {
        id: '',
        username: '',
        password: '',
        email: 'a@b.com',
        mobile: '13345678910'
      },
      editUserForm: {
        username: '',
        email: '',
        mobile: '',
        id: null
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '密码长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /\w+[@]\w+[.]\w{2,3}/,
            message: '请输入合法的邮箱地址',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[345678]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted () {
    this.init()
    // 获取全部角色列表
    getAllRolesList()
      .then(res => {
        console.log(res)
        this.rolesList = res.data.data
        if (res.data.meta.status === 200) {
        } else {
          console.log(res.data.meta.msg)
        }
      })
      .catch(err => {
        console.log(err)
      })
  },
  methods: {
    // 封装数据初始化的方法
    init () {
      getUsers({
        query: this.query,
        pagenum: this.pagenum,
        pagesize: this.pagesize
      })
        .then(res => {
          // console.log(res)
          this.userInfo = res.data.data.users
          this.total = res.data.data.total
          // this.pagenum = res.data.data.pagenum  --  这句是多余的
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleSizeChange (val) {
      //   console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.init()
    },
    handleCurrentChange (val) {
      //   console.log(`当前页: ${val}`)
      this.pagenum = val
      this.init()
    },
    // 实现筛选
    search () {
      this.pagenum = 1
      this.init()
    },
    // 添加新用户
    addNewUser () {
      // console.log(this.$refs)
      // 再次进行验证
      this.$refs.addForm.validate(valid => {
        // console.log(valid)
        if (valid === true) {
          askAddNewUser(this.addForm)
            .then(res => {
              console.log(res)
              if (res.data.meta.status === 201) {
                Message({
                  type: 'success',
                  message: res.data.meta.msg
                })
                this.init()
                this.addDialogFormVisible = false
                this.$refs.addForm.resetFields()
              } else {
                Message({
                  type: 'warning',
                  message: res.data.meta.msg
                })
              }
            })
            .catch(err => {
              Message({
                type: 'error',
                message: err
              })
            })
        } else {
          return false
        }
      })
    },
    // 显示配置用户角色弹窗
    showRoleFormVisible (data) {
      // console.log(data)
      this.configureRoleFormVisible = true
      this.configureForm.username = data.username
      this.configureForm.id = data.id
      this.configureForm.rid = data.rid
    },
    // 修改提交用户角色信息
    configureUserRoleSub () {
      if (!this.configureForm.rid) {
        Message({
          type: 'warning',
          message: '配置的角色不能为空'
        })
        return false
      }
      configureUserRole(this.configureForm.id, this.configureForm.rid)
        .then(res => {
          // console.log(res)
          if (res.data.meta.status === 200) {
            // this.configureForm.rid = res.data.data.rid
            Message({
              type: 'success',
              message: res.data.meta.msg
            })
            console.log(this.configureForm.rid)
            console.log(res.data.data.rid)
            this.init()
            this.configureRoleFormVisible = false
          } else {
            Message({
              type: 'warning',
              message: res.data.meta.msg
            })
          }
        })
        .catch(err => {
          Message({
            type: 'error',
            message: err
          })
        })
    },
    // 修改用户状态
    editUserStatus (uld, type) {
      // console.log(uld, type)
      updateUserState(uld, type)
        .then(res => {
          // console.log(res)
          if (res.data.meta.status === 200) {
            Message({
              type: 'success',
              message: res.data.meta.msg
            })
          } else {
            Message({
              type: 'warning',
              message: res.data.meta.msg
            })
          }
        })
        .catch(err => {
          Message({
            type: 'error',
            message: err
          })
        })
    },
    // 删除用户数据
    deluser (id) {
      // console.log(id)
      // 调用element的$confirm方法即可打开消息提示
      this.$confirm('此操作将永久删除该文件, 是否继续?', '温馨提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          // console.log(111) 点击确定后触发
          // 请求接口
          // 删除后total-1,除以页容量向上取整得到最大页码数，小于操作前当前页，则应改变最大页
          // 判断本次删除之后，当前页还有没有数据，如果有数据，就保持页码为当前页，否则就到上一页
          this.pagenum = Math.ceil((this.total - 1) / this.pagesize) < this.pagenum
            ? --this.pagenum
            : this.pagenum
          console.log(this.pagenum)
          delUserById(id)
            .then(res => {
              // console.log(res)
              if (res.data.meta.status === 200) {
                Message({
                  type: 'success',
                  message: res.data.meta.msg
                })
                this.init()
              } else {
                Message({
                  type: 'warning',
                  message: res.data.meta.msg
                })
              }
            })
            .catch(err1 => {
              console.log(err1)
              Message({
                type: 'error',
                message: '删除失败'
              })
            })
        })
        // 没有这一步不影响但是会报错，
        .catch(() => {
          Message({
            type: 'info',
            message: '已取消删除'
          })
          return false
        })
    },
    // 编辑用户数据编辑窗口的弹出和旧数据的展示
    editUser (data) {
      this.editDialogFormVisible = true
      // console.log(data)
      // 展示旧数据 ,通过scope.row拿到之前的旧数据并添加到弹窗  -- 担心直接赋值会影响scop.row里面的数据，进行深度拷贝
      var { username, email, mobile, id } = data
      this.editUserForm = {
        username,
        email,
        mobile,
        id
      }
      // this.editUserForm = data
      console.log(this.editUserForm)
    },
    // 编辑用户数据请求接口
    confirmEditUser () {
      this.$refs.editUserForm.validate(valid => {
        if (valid) {
          // console.log(valid)
          console.log(this.editUserForm)
          editUserById(this.editUserForm)
            .then(res => {
              // console.log(res)
              if (res.data.meta.status === 200) {
                Message({
                  type: 'success',
                  message: res.data.meta.msg
                })
                this.init()
                this.editDialogFormVisible = false
              } else {
                Message({
                  type: 'warning',
                  message: res.data.meta.msg
                })
              }
            })
            .catch(err => {
              Message({
                type: 'error',
                message: err
              })
            })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
